<!--
 * @Description: In User Settings Edit
 * @Author: your name
 * @Date: 2019-05-17 19:37:02
 * @LastEditTime: 2019-09-01 16:44:15
 * @LastEditors: Please set LastEditors
 -->
<template>
    <div class="layout">
        <Layout>
            <Content :style="{padding: ' 0 24px', minHeight: '650px', background: '#fff'}">
                <div style="overflow:hidden">
                    <Row type="flex" class="code-row-bg" :gutter="16">
                        <Col>
                            <Button type="primary" @click="addConfigureBt = true;cancelsmtConfigureInfo('formValidate');addConfigureBtTitle = '新增配置'">
                                <Icon type="md-add" />
                               		 添加写入文件配置
                            </Button>
                        </Col>
                        <Col>
                            <!--<Button type="primary" @click="uploadConfigureBt = true;cancelsmtConfigureInfo('formValidate');uploadConfigureBtTitle = '导入配置'">
                                <Icon type="ios-cloud-upload-outline" />
                                	导入写入文件配置
                            </Button>-->
                            <Input suffix="ios-search" placeholder="请输入名称" style="width:300px" v-model="btnNameValue" @on-change="getQgaWriteInfoList" />
                            <Button type="primary"  @click="getQgaWriteInfoList">搜索</Button>
                         </Col>
                    </Row>
                </div>
                <Table stripe :columns="tbTitle" :data="tbData" style="margin-top:10px;"></Table> 
                <Page :total="pageCount" show-total show-elevator @on-change="change" style="margin-top:10px; text-align:center;"/>
            </Content>
        </Layout>
        <Modal v-model="addConfigureBt" :title="addConfigureBtTitle" :loading="loading" :mask-closable="false"
                @on-ok="submitConfigureInfo('formValidate')"  @on-cancel="cancelsmtConfigureInfo('formValidate')">
            <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="95">
                <FormItem label="配置名称" prop="name">
                    <Input v-model.trim="formValidate.name" placeholder="请输入配置名称"></Input>
                </FormItem>
                <FormItem label="操作系统" prop="osType">
                    <RadioGroup v-model="formValidate.osType">
                        <Radio label="Windows">Windows</Radio>
                        <Radio label="Linux">Linux</Radio>
                    </RadioGroup>
                </FormItem>
                <FormItem label="路径" prop="path">
                    <Input v-model.trim="formValidate.path" placeholder="请输入配置路径"></Input>
                </FormItem>
                <FormItem label="写入分类" prop="category" v-if="addConfigureBt">
                    <Select filterable v-model="formValidate.category" placeholder="请选择写入分类">
                        <Option value="dynamic_route_cfg">动态路由器配置</Option>
                        <Option value="simulation_flow_chara">流量仿真配置</Option>
                        <Option value="user_behavior">用户行为配置</Option>
                        <Option value="application_service_cfg">应用服务配置</Option>
                        <Option value="simulation_disperse">离散事件仿真配置</Option>
                        <!-- <Option value="qga_common">qga通用模板</Option> -->
                        <Option value="qga_common">其他配置</Option>
                    </Select>
                </FormItem>
                <FormItem label="写入方式" prop="type" v-if="addConfigureBt">
                    <Select filterable v-model="formValidate.type" placeholder="请选择写入方式">
                        <Option value="w">覆盖写入</Option>
                        <Option value="a">追加写入</Option>
                    </Select>
                </FormItem>
                <FormItem label="写入内容" prop="content">
                    <Input v-model.trim="formValidate.content" type="textarea" :rows="2" :maxlength="6000"></Input>
                </FormItem>
                <FormItem label="配置描述" prop="visibility">
                    <RadioGroup v-model="formValidate.visibility">
		              <Radio label="share">共享</Radio>
		              <Radio label="2">私有</Radio>
		            </RadioGroup>
                </FormItem>
                <FormItem label="配置描述" prop="description">
                    <Input v-model.trim="formValidate.description" type="textarea" :rows="2" :maxlength="200"></Input>
                </FormItem>
            </Form>
        </Modal>
        <Modal v-model="uploadConfigureBt" :title="uploadConfigureBtTitle" :loading="uploadloading" :mask-closable="false"
                @on-ok="uploadConfigureInfo('formValidate')"  @on-cancel="cancelsmtConfigureInfo('formValidate')">
            <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="95">
                <FormItem label="配置名称" prop="name">
                    <Input v-model.trim="formValidate.name" placeholder="请输入配置名称"></Input>
                </FormItem>
                <FormItem label="写入分类" prop="category" v-if="uploadConfigureBt">
                    <Select filterable v-model="formValidate.category" placeholder="请选择写入分类">
                        <Option value="dynamic_route_cfg">动态路由器配置</Option>
                        <Option value="simulation_flow_chara">流量仿真配置</Option>
                        <Option value="user_behavior">用户行为配置</Option>
                        <Option value="application_service_cfg">应用服务配置</Option>
                        <Option value="simulation_disperse">离散事件仿真配置</Option>
                        <!-- <Option value="qga_common">qga通用模板</Option> -->
                        <Option value="qga_common">其他配置</Option>
                    </Select>
                </FormItem>
                <FormItem label="配置描述" prop="description">
                    <Input v-model.trim="formValidate.description" type="textarea" :rows="2"></Input>
                </FormItem>
                <FormItem label="选择文件" prop="file">
                    <Upload
                        ref="upload"
                        :before-upload="handleBeforeUpload"
                        :show-upload-list="false"
                        :action="baseUrl">
                        <Button icon="ios-cloud-upload-outline" >Upload files</Button>
                    </Upload>
                    <div class="demo-upload-list">
                        <ul class="ivu-upload-list">
                            <li class="ivu-upload-list-file" v-for="(item,index) in uploadFileList" :key="index">
                                <span><i class="ivu-icon ivu-icon-ios-image"></i>{{item.name}}</span> 
                                    <i class="ivu-icon ivu-icon-ios-close ivu-upload-list-remove" style="display: none;position:relative;top:8px" @click="handleRemove(item)"></i> 
                            </li>
                        </ul>
                    </div>
                </FormItem>
            </Form>
        </Modal>
        <Modal v-model="delConfigureMd" title="删除配置" @on-ok="ok4delConfigureMd" :mask-closable="false">
            <div style="text-align:center;font-size:15px;">确认要删除配置：" <strong>{{this.currConfigureName}}</strong> " 吗？</div>
        </Modal>
        <Modal v-model="detailConfigureMd" title="配置详情" :mask-closable="false">
             <Table stripe :columns="detailTbTitle" :data="detailTbData" :show-header="false"></Table>
        </Modal>
    </div>
</template>
<!--<script src="../../../static/const.js"></script>-->
<script>
    const validateName = (rule, value, callback) => {
        var myReg = /[~!！@#$%^&*()/\|,<>?"'“‘();:+=\[\]{}]/;
        value = value.replace(/\s*/g,"");
        if(!value){
            callback("请填写名字");
        }else{
            if (myReg.test(value)) {
                callback("名字不能包含特殊字符");
            } else {
                callback();
            }
        }
    };
    import axios from '@/libs/axios1'
    // import axios from '@/libs/api.request'
    //import fileSaver from 'file-saver'
    export default {
        name:'qgaWriteCollect',
        data(){
            return{
                btnNameValue:'',
                tbTitle: [
                    { 
                    	title: '配置名称',
                        key: 'name',
//                      render: (h, params) => {
//                          return h('div', [
//                              h('a', {
//                                  props: {size: 'small'},
//                                  style: {marginRight: '5px'},
//                                  on: {
//                                          click: () => {
//                                              this.getConfigureInfo(params)
//                                      }
//                                  }
//                              }, params.row.name)
//                          ]);
//                      }
                    },
                    { 
                    	title: '操作系统', 
                    	key: 'osType'
                    },
                    { 
                    	title: '路径', 
                    	key: 'path',
                    	render:(h,params) => {
                    		return h('span',params.row.data.path)
                    	}
                    },
                    { 
                    	title: '内容',
                    	key: 'content'
                    },
                    { 
                    	title: '写入方式', 
                    	key: 'category'
                    },
                    { 
                    	title: '写入分类',
                    	key: 'type'
                    },
                    { 
                    	title: '权限', 
                    	key: 'visibility',
                    	render:(h,params) =>{
                    		return h('span',params.row.visibility == 'share' ? '共享' : '私有')
                    	}
                    },
                    { 
                    	title: '创建者', 
                    	key: 'creatorName'
                    },
                    { 
                    	title: '描述', 
                    	key: 'description'
                    },
                    {
                        title: '操作',
                        key: 'operation',
                        width:150,
                        render: (h, params) => {
                            return h('div', [
//                              h('Button', {
//                                  props: {size: 'small',type:'primary'},
//                                  style: {marginRight: '5px'},
//                                  on: {
//                                      click: () => {
//                                          this.exportInfo(params)
//                                      }
//                                  }
//                              }, '导出'),
                                h('Button', {
                                    props: {size: 'small',type:'primary'},
                                    style: {marginRight: '5px'},
                                    on: {
                                        click: () => {
                                            this.modifyInfo(params)
                                        }
                                    }
                                }, '修改'),
                                h('Button', {
                                    props: {size: 'small',type:'error'},
                                    style: {marginRight: '5px'},
                                    on: {
                                        click: () => {
                                            this.removeInfo(params)
                                        }
                                    }
                                }, '删除')
                            ]);
                        }
                    }
                ],
                formValidate: {
                    name: '',
                    osType: 'Windows',
                    path: '',
                    category: '',
                    type: '',
                    content: '',
                    description: '',
                    visibility:'private'
                },
                ruleValidate: {
                    name: [
                        { required: true, message: '', trigger: 'change' ,validator:validateName }
                    ],
                    osType: [
                        { required: true, message: '请选择操作系统类型！', trigger: 'change' }
                    ],
                    path: [
                        { required: true, message: '路径不能为空！', trigger: 'change' }
                    ],
                    category: [
                        { required: true, message: '请选择写入分类！', trigger: 'change' }
                    ],
                    type: [
                        { required: true, message: '请选择写入方式！', trigger: 'change' }
                    ],
                    content: [
                        { required: true, message: '请填写入内容！', trigger: 'change' }
                    ]   
                },
                tbData: [],
                detailTbData:[],
                loading: true,
                addConfigureBt: false,
                addConfigureBtTitle: '新增配置',
                uploadloading: true,
                uploadConfigureBt: false,
                uploadConfigureBtTitle: '导入配置',
                currPage: 1,
                pageCount: 0,
                detailConfigureMd: false,
                detailTbTitle:[{
                    title:"属性",key:"attr"
                },{
                    title:"值",key:"value"
                }],
                configureDetailInfo:{},
                delConfigureMd: false,
                currConfigureId: '',
                currConfigureName: '',
                baseUrl: '',
                checkCode: 0,
                uploadFileList: []
            }
        },
        created: function () {
            this.getQgaWriteInfoList();
        },
        mounted (){
            this.uploadFileList = this.$refs.upload.fileList;
        },
        methods:{
            change: function (page) {
                this.currPage = page;
                this.getQgaWriteInfoList();
            },
            getQgaWriteInfoList(){
                let _this = this;
                axios({
                    url: `/tasktemplate/item`,
                    method: 'get',
                    params: {
                        page: _this.currPage,
                        size: 10,
                        operation: 'qga_write',
                        name:_this.btnNameValue
                    }
                }).then(function (response) {
                    if(response.code != '1'){
                        _this.$Message.warning(response.data.message);
                        _this.tbData = [];
                    }else{
                         _this.tbData = response.data.list.map(function(item){
                             return {
                                 id:item.id,
                                 name:item.name,
                                 path:item.data.path,
                                 type:_this.fliterType(item.data.type),
                                 category:_this.fliterType(item.category),
                                 osType:item.data.osType,
                                 description:item.description,
                                 content:item.data.content,
                                 creatorName:item.creatorName,
                                 // 待导出的json数据
                                 data:item.data
                             }
                         })
                         _this.pageCount = response.data.count;
                    }
                });
            },
            getConfigureInfo(params){
                let _this = this;
                _this.detailConfigureMd = true;
                _this.currConfigureId =  params.row.id;
                axios({
                    url: `/tasktemplate/item/` + _this.currConfigureId,
                    method: 'get',
                }).then(function (response) {
                    if(response.code != '1'){
                        _this.$Message.warning(response.message);
                    }else{
                        _this.configureDetailInfo = response.data;
                        let tempType = _this.fliterType(_this.configureDetailInfo.data.type);
                        let tempCategory = _this.fliterType(_this.configureDetailInfo.category);
                        _this.detailTbData =  [
                                {attr:"配置名称",value: _this.configureDetailInfo.name},
                                {attr:"操作系统",value: _this.configureDetailInfo.data.osType},
                                {attr:"路径",value: _this.configureDetailInfo.data.path},
                                {attr:"写入分类",value: tempCategory},
                                {attr:"写入方式",value: tempType},
                                {attr:"内容",value: _this.configureDetailInfo.data.content},
                                {attr:"配置描述",value: _this.configureDetailInfo.description},
                                {attr:"创建时间",value: _this.configureDetailInfo.createTime},
                                {attr:"创建者",value: _this.configureDetailInfo.creatorName},
                                {attr:"修改时间",value: _this.configureDetailInfo.lastModifyTime}
                                // {attr:"修改者",value: _this.configureDetailInfo.modifior}
                             ]
                    }
                });
            },
            submitConfigureInfo(name){
                let _this = this;
                this.$refs[name].validate((valid) => {
                    if (valid) {
                        let data = _this.formValidate; 
                        data.name = data.name.replace(/\s*/g,"");       
                        if(_this.addConfigureBtTitle == '新增配置'){
                            axios({
                                url: `/tasktemplate/item/add/qga_write`,
                                method: 'post',
                                data:data
                            }).then(function (response) {
                                if(response.code != '1'){
                                    _this.$Message.error(response.message);
                                     _this.loading = false;
                                    _this.$nextTick(() => {
                                        _this.loading = true;
                                    });
                                }else{
                                    _this.$Message.success('新增配置完成!'); 
                                     _this.loading = false;
                                    _this.$nextTick(() => {
                                        _this.loading = true;
                                    });                                  
                                    _this.getQgaWriteInfoList();
                                    _this.addConfigureBt = false;
                                    _this.cancelsmtConfigureInfo('formValidate');
                                }
                                
                                
                            });
                        }else{//修改配置
                            axios({
                                url: `/tasktemplate/item/update/qga_write/`+_this.currConfigureId,
                                method: 'put',
                                data:data
                            }).then(function (response) {
                                if(response.code != '1'){
                                    _this.$Message.error(response.message);
                                     _this.loading = false;
                                    _this.$nextTick(() => {
                                        _this.loading = true;
                                    });
                                }else{
                                    _this.$Message.success('修改配置完成!');
                                     _this.loading = false;
                                    _this.$nextTick(() => {
                                        _this.loading = true;
                                    });
                                    _this.getQgaWriteInfoList();
                                    _this.addConfigureBt = false;
                                    _this.cancelsmtConfigureInfo('formValidate');
                                }
                                
                                
                            });
                        }                       
                    } else {
                        _this.loading = false;
                        _this.$nextTick(() => {
                            _this.loading = true;
                        });
                        _this.$Message.info("请检查内容是否填写完整！");
                    }
                })
            },
            uploadConfigureInfo(name){
                let _this = this;
                this.$refs[name].validate((valid) => {
                    if(_this.uploadFileList.length == 0){
                        _this.$Notice.warning({
                            title: '配置信息为空',
                            desc: '请上传一个配置文件！'
                        });
                        _this.uploadloading = false;
                        _this.$nextTick(() => {
                            _this.uploadloading = true;
                        });
                        return;
                    }
                    if (valid) {
                        let formData = new FormData();
                        _this.formValidate.name =  _this.formValidate.name.replace(/\s*/g,"");
                        formData.append("operation", 'qga_write');
                        formData.append("name", _this.formValidate.name);
                        formData.append("category", _this.formValidate.category);
                        formData.append("description", _this.formValidate.description);
                        _this.uploadFileList.forEach(file => formData.append('file', file));      
                        axios({
                                url: `/tasktemplate/item/import/qga_write`,
                                method: 'post',
                                data:formData,
                                headers: {'Content-Type': 'multipart/form-data'},
                                timeout:0,
                            }).then(function (response) {
                                if(response.code != '1'){
                                    _this.$Message.error(response.message);
                                    _this.uploadloading = false;
                                    _this.$nextTick(() => {
                                        _this.uploadloading = true;
                                    });
                                }else{
                                    _this.$Message.success('导入配置完成!');  
                                    _this.uploadloading = false;
                                    _this.$nextTick(() => {
                                        _this.uploadloading = true;
                                    });                                 
                                    _this.getQgaWriteInfoList();
                                    _this.uploadConfigureBt = false;
                                    _this.cancelsmtConfigureInfo('formValidate');
                                }
                            });                     
                    } else {
                        _this.uploadloading = false;
                        _this.$nextTick(() => {
                            _this.uploadloading = true;
                        });
                        this.$Message.info("请检查内容是否填写完整！");
                    }
                })
            },
            cancelsmtConfigureInfo(name){
                this.$refs[name].resetFields();
                this.formValidate = {
                    name: '',
                    osType: 'Windows',
                    path: '',
                    category: '',
                    type: '',
                    content: '',
                    description: ''
                };
                this.uploadFileList = [];
            },
            modifyInfo(params){
                let _this = this;
                _this.currConfigureId =  params.row.id;
                axios({
                    url: `/tasktemplate/item/` + _this.currConfigureId,
                    method: 'get'
                }).then(function (response) {
                    if(response.code != '1'){
                        _this.$Message.error(response.message);
                    }else{  
                        _this.formValidate ={
                            name: response.data.name,
                            osType: response.data.data.osType,
                            category: response.data.category,
                            path: response.data.data.path,
                            type: response.data.data.type,
                            content: response.data.data.content,
                            description: response.data.description,
                            visibility:response.data.visibility
                         };
                        _this.addConfigureBtTitle = "修改配置";
                        _this.addConfigureBt = true;
                    }
                });
            },
            removeInfo(params){
                let _this = this;
                _this.delConfigureMd = true;
                _this.currConfigureId =  params.row.id;
                _this.currConfigureName =  params.row.name;
            },
            ok4delConfigureMd(){
                let _this = this;
                axios({
                    url: `/tasktemplate/item/` + _this.currConfigureId,
                    method: 'delete'
                }).then(function (response) {
                    if(response.code != '1'){
                        _this.$Message.error(response.message);
                    }else{
                         _this.$Message.success("删除配置完成！");
                         _this.getQgaWriteInfoList();
                    }
                });
                _this.delConfigureMd = false;
            },
            exportInfo(params){
                const data = JSON.stringify(params.row.data)
                const blob = new Blob([data], {type: ''}); 
                fileSaver.saveAs(blob, params.row.name+'.json');
            },
            fliterType(value){
                //if(!value) return '-'
                if(value == "w"){
                    return "覆盖写入";
                }else if(value == 'a'){
                    return "追加写入";
                }else if(value == 'simulation_disperse'){
                    return "离散事件仿真";
                }else if(value == 'simulation_flow_chara'){
                    return "流量仿真";
                }else if(value == 'user_behavior'){
                    return "用户行为";
                }else if(value == 'qga_common'){
                    return "其他";
                }else if(value == 'application_service_cfg'){
                    return "应用服务";
                }else if(value == 'dynamic_route_cfg'){
                    return "动态路由";
                }
            },
            //导入相关
            handleRemove(file) {
                this.$refs.upload.fileList  =[];
                this.uploadFileList = [];
                const fileList = this.$refs.upload.fileList;
                this.$refs.upload.fileList.splice(fileList.indexOf(file), 1);
            },
            handleFormatError (file) {
                this.$Notice.warning({
                    title: '文件格式不正确',
                    desc: '文件 ' + file.name + ' 格式不正确，请上传JSON格式的文件。'
                });
                this.checkCode = 1;
            },
            handleMaxSize (file) {
                this.$Notice.warning({
                    title: '超出文件大小限制',
                    desc: '文件 ' + file.name + ' 太大，不能超过 1M。'
                });
                this.checkCode = 1;
            },
            handleCNName (file) {
                this.$Notice.warning({
                    title: '文件名称',
                    desc: '请不要使用含有中文的文件名。'
                });
                this.checkCode = 1;
            },
            handleFile (file) {
                this.$Notice.warning({
                    title: '已存在文件',
                    desc: '只能上传一个配置文件！'
                });
                this.checkCode = 1;
            },
            handleBeforeUpload (file) {
                // const fileSize = file.size / 1024 / 1024 > this.$store.state.common.fileMax;
                // if(fileSize){
                // this.$Message.error({
                //     content: `文件大小不能大于${this.$store.state.common.fileMax}M`,
                //     duration: 2
                // });
                // return false;
                // }
                const _this = this;
                var str=file.name.split("\\")[file.name.split("\\").length-1];
                var re=/[\u0391-\uFFE5]+/g
                if (str.match(re)!=null){
                     _this.handleCNName (file);
                }
                if(_this.uploadFileList.length >= 1){
                    _this.handleFile (file);
                }
                if( (file.size / 1024) > 1024){//kb
                    _this.handleMaxSize (file); 
                }
                if(file.type !="application/json"){
                     _this.handleFormatError (file);
                }
                if( _this.checkCode == 0){
                    _this.uploadFileList.push(file);
                }else{
                    _this.checkCode = 0;
                }
                return false;
            }

        }
    
    }
</script>

<style scoped>
.ivu-upload-list-remove{
    display:block!important;
}
</style>
